#!/usr/bin/env python
# coding=utf8

"""
该日志类可以把不同级别的日志输出到不同的日志文件中
"""
import datetime
import inspect
import logging
import os
import threading
import time
from logging import handlers as hl

from util import fileUtil

level_info = {
    logging.DEBUG: {
        "name": "/Log/work_hour_fill.{}.log",
        "backupCount": 7,
        "maxBytes": 1024 * 1024 * 30
    },
    logging.INFO: {
        "name": "/Log/work_hour_fill.{}.log",
        "backupCount": 7,
        "maxBytes": 1024 * 1024 * 30
    },
    logging.ERROR: {
        "name": "/Log/work_hour_fill.{}.log",
        "backupCount": 7,
        "maxBytes": 1024 * 1024 * 30
    },
}

handlers = {}


def createHandlers():
    ct = time.time()
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y-%m-%d", local_time)
    logLevels = level_info.keys()
    for level in logLevels:
        info_level_ = level_info[level]
        filename = fileUtil.getRootPath() + info_level_['name'].format(data_head)
        dir = os.path.abspath(os.path.dirname(filename))
        fileUtil.mkdir(dir)
        """
        filename:文件名
        maxBytes:"单个保留的最大字节数"
        backupCount:"超过单个文件最大字节数后，生成备份文件数 work_hour_fill-debug.log.2020-01-07.1，.2,.3，
        当超过文件数以后，后续文件都将写入work_hour_fill-debug.log.2020-01-07"
        """
        handlers[level] = hl.RotatingFileHandler(filename=filename, maxBytes=info_level_['maxBytes'],
                                                 backupCount=7, encoding='utf-8')


# 加载模块时创建全局变量
createHandlers()


class Logger(object):
    _instance_lock = threading.Lock()

    def printfNow(self):
        return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S.%f')

    def __new__(cls, *args, **kwargs):
        if not hasattr(Logger, "_instance_"):
            with Logger._instance_lock:
                if not hasattr(Logger, "_instance_"):
                    setattr(Logger, "_instance_", object.__new__(cls))
                    getattr(Logger, "_instance_").__init_logger()
        return getattr(Logger, "_instance_")

    def __init__(self, level=logging.DEBUG):
        pass

    def __init_logger(self, level=logging.DEBUG):
        self.__loggers = {}
        logLevels = handlers.keys()
        for level in logLevels:
            logger = logging.getLogger(str(level))
            logger.addHandler(handlers[level])
            logger.addHandler(logging.StreamHandler())
            logger.setLevel(level)
            self.__loggers.update({level: logger})

    def getLogMessage(self, level, message):
        frame, filename, lineNo, functionName, code, unknowField = inspect.stack()[2]
        '''日志格式：[时间] [类型] [记录代码] 信息'''
        return "[%s] [%s] %s - [line %s] - %s %s" % (
            self.printfNow(), level.upper(), filename, lineNo, functionName, message)

    def debug(self, message):
        message = self.getLogMessage("debug", message)
        self.__loggers[logging.DEBUG].debug(message)

    def info(self, message):
        message = self.getLogMessage("info", message)
        self.__loggers[logging.INFO].info(message)

    def error(self, message):
        message = self.getLogMessage("error", message)
        self.__loggers[logging.ERROR].error(message)

    def warning(self, message):
        message = self.getLogMessage("warning", message)
        self.__loggers[logging.ERROR].warning(message)

    def critical(self, message):
        message = self.getLogMessage("critical", message)
        self.__loggers[logging.ERROR].warning(message)
